/**
 *
 */
package util;

import com.dangdi.controller.websokectHandler;
import com.gexin.fastjson.JSON;
import com.sun.jna.Native;
import com.sun.jna.win32.StdCallLibrary;

import org.apache.http.HttpResponse;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * @项目 ddBook
 * @作者 User
 * @时间 2018年7月11日 下午4:54:32
 * @方法 ReaderCardDervice
 * @路径
 */
public class ReaderCardDervice implements Runnable {
    private static int g_hDevice[] = new int[]{-1}; //hDevice must init as -1
    private static String pUID = "";
    private static boolean flag = false;
    private int statusCode = -1;
    private int sssTatus = 0;
    private String ip = "";
    private String sUID = "";
    final String filePath = System.getProperty("user.dir") + "\\conf.properties";
    private PropertiesUtils utils = new PropertiesUtils(filePath);

    public String getIp() {
        return ip;
    }

    websokectHandler sokect = new websokectHandler();
    private int actionType = 0;

    public String getsUID() {
        return sUID;
    }

    public void setsUID(String sUID) {
        this.sUID = sUID;
    }

    public int getSssTatus() {
        return sssTatus;
    }

    public int getActionType() {
        return actionType;
    }

    public void setActionType(int actionType) {
        this.actionType = actionType;
    }

    public void setSssTatus(int sssTatus) {
        this.sssTatus = sssTatus;
    }

    public static boolean isFlag() {
        return flag;
    }

    public static void setFlag(boolean flag) {
        ReaderCardDervice.flag = flag;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public interface ReaderLib extends StdCallLibrary {
        ReaderLib INSTANCE = (ReaderLib) Native.loadLibrary(System.getProperty("user.dir") + "\\libs\\readerCardLibs\\hfrdapi", ReaderLib.class);

        int Sys_Open(int[] device, int index, short vid, short pid);

        int Sys_Close(int[] device);

        boolean Sys_IsOpen(int device);

        int Sys_SetLight(int device, byte color);

        int Sys_SetBuzzer(int device, byte msec);

        int Sys_SetAntenna(int device, byte mode);

        int Sys_InitType(int device, byte type);

        int TyA_Request(int device, byte mode, short[] pTagType);

        int TyA_Anticollision(int device, byte bcnt, byte[] pSnr, byte[] pLen);

        int TyA_Select(int device, byte[] pSnr, byte snrLen, byte[] pSak);

        int TyA_Halt(int device);

        int TyA_CS_Authentication2(int device, byte mode, byte block, byte[] pKey);

        int TyA_CS_Read(int device, byte block, byte[] pData, byte[] pLen);

        int TyA_CS_Write(int device, byte block, byte[] pData);

        int TyA_UID_Write(int device, byte[] pData);

        int I15693_Inventory(int device, byte[] pDate, byte[] pLen);

        int I15693_Inventorys(int device, byte[] pDate, byte[] pLen);

        int I15693_Select(int device, byte[] pUID);

        int I15693_GetSystemInformation(int device, byte mode, byte[] pUID, byte[] pData, byte[] pLen);

        int I15693_Read(int device, byte mode, byte[] pUID, byte block, byte number, byte[] pData, byte[] pLen);
    }

    /**
     */


    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        flag = false;
        // TODO Auto-generated method stub
        setStatusCode(-1);
        int status;
        boolean bStatus;
        bStatus = ReaderLib.INSTANCE.Sys_IsOpen(g_hDevice[0]);
        if (bStatus == true) {
            status = ReaderLib.INSTANCE.Sys_Close(g_hDevice);
            if (status != 0) {
                System.out.println("设备关闭失败！");
            }
        }

        //Connect
        status = ReaderLib.INSTANCE.Sys_Open(g_hDevice, 0, (short) 0x0416, (short) 0x8020);
        if (status != 0) {
            System.out.println("设备开启失败！");
            System.out.println(status);
            flag = true;
        }

        status = ReaderLib.INSTANCE.Sys_SetAntenna(g_hDevice[0], (byte) 0);
        if (status != 0) {
            System.out.println("设置天线失败！");

        }
        try {
            Thread.sleep(5);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        status = ReaderLib.INSTANCE.Sys_InitType(g_hDevice[0], (byte) 'A');
        if (status != 0) {
            System.out.println("设置协议模式失败！");
            return;
        }
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        status = ReaderLib.INSTANCE.Sys_SetAntenna(g_hDevice[0], (byte) 1);
        if (status != 0) {
            System.out.println("设置非接触工作失败！");
            return;
        }
        byte mode = 0x52;
        short[] TagType = new short[1];
        byte bcnt = 0;
        byte snr[] = new byte[16];
        byte len[] = new byte[1];
        byte sak[] = new byte[1];
        flag = true;
        while (flag) {
            setStatusCode(0);
            status = ReaderLib.INSTANCE.TyA_Request(g_hDevice[0], mode, TagType);//search all card
            if (status != 0) {
                clearPUID();
                continue;
            }
            status = ReaderLib.INSTANCE.TyA_Anticollision(g_hDevice[0], bcnt, snr, len);//return serial number of card
            if (status != 0 || len[0] != 4) {
                clearPUID();
                continue;
            }

            String str = "";

            for (int i = 0; i < 4; i++) {
                str = str + String.format("%02X", snr[i]);
            }
            if (pUID.equals("0")) {
                try {
                    if (!str.equals("00000000")) {
                        sendCar(str);
                    } else {
                        System.out.println("收到干扰");
                    }
                } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (actionType == 1) {
                if (!str.equals(sUID)) {
                    if (!str.equals("00000000")) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("sUid", str);
                        map.put("from", "importReader");
                        sokect.onMessage(JSON.toJSONString(map));
                    }

                }
            }
            sUID = str;
            pUID = str;
            //System.out.println(str);
        }
        status = ReaderLib.INSTANCE.Sys_Close(g_hDevice);
        setStatusCode(-1);

    }


    public void closeDevice() {
        flag = false;
    }

    public void clearPUID() {
        pUID = "0";
    }

    public Map<String, Object> sendCar(String uID) throws URISyntaxException, IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("reader_rfid", uID);
        String filePath = System.getProperty("user.dir") + "\\conf.properties";
        //定义修改配置文件的工具类
        PropertiesUtils utils = new PropertiesUtils(filePath);
        map.put("machine_type", utils.getKeyValue("terminalSymbol"));
        map.put("terminalNumber", utils.getKeyValue("terminalNumber"));
        map.put("from", "reader");
        HttpClientUtil client = new HttpClientUtil();
//		HttpResponse response=client.HttoPost(map, "http://"+getIp()+":8080/DangD/getReaderRecordByReaderCardNum");
        if (actionType == 0) {
            String url = "http://" + utils.getKeyValue("serverIP") + ":" + utils.getKeyValue("serverPort") + "/DangD/getReaderRecordByReaderCardNum";
            HttpResponse response = client.HttoPost(map, url);
            System.out.println(response.getStatusLine().getStatusCode());
            sokect.onMessage(JSON.toJSONString(map));
        }
        return map;
    }

    public void closeReaderDervice() {
        flag = false;
    }


}
